<template>
  <!-- 设备管理 -->
  <div id="eqRepairEditDiv">
    <GoBack content="运行记录" :backUrl="backUrl" :planId="planId" :pageSize="pageSize" :pageIndex="pageIndex"></GoBack>

    <el-container>
      <div class="padding-sm" style="width: 70%; padding-top: 10px">
        <el-scrollbar style="height: 100%">
          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">设备信息
                <vxe-button v-if="checkEquiptShow" @click="checkEquiptDialog" type="text" class="button-blue margin-left-xs" icon="vxe-icon-square-plus">选择设备</vxe-button>
              </div>
            </template>
            <el-descriptions-item label="设备编码">
              <vxe-input disabled v-model="runningform.equiptCode"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="设备名称">
              <vxe-input v-model="runningform.equiptName"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="设备型号">
              <vxe-input v-model="runningform.specification"></vxe-input>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions :column="3" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
            <template #title>
              <div class="smallToolTitle">运行信息</div>
            </template>
            <el-descriptions-item label="运行单号">
              <vxe-input disabled v-model="runningform.runningNo" placeholder="自动生成"></vxe-input>
            </el-descriptions-item>

            <el-descriptions-item label="班次">
              <vxe-select v-model="runningform.classes" placeholder="请选择班次" style="width: 62%;">
                <vxe-option v-for="typeObj in runningClassesList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item label="开机人">
              <vxe-select v-model="runningform.startPersonId" placeholder="请选择开机人" style="width: 62%;" filterable transfer @change='changeStartPerson'>
                <vxe-option v-for="typeObj in personList" :key="typeObj.id" :label="typeObj.name" :value="typeObj.id" />
              </vxe-select>
            </el-descriptions-item>
            <el-descriptions-item label="关机人">
              <vxe-select v-model="runningform.shutPersonId" placeholder="请选择关机人" style="width: 62%;" filterable transfer @change='changeShutPerson'>
                <vxe-option v-for="typeObj in personList" :key="typeObj.id" :label="typeObj.name" :value="typeObj.id" />
              </vxe-select>
            </el-descriptions-item>

            <el-descriptions-item label="开始时间">
              <vxe-input v-model="runningform.startDate" placeholder="日期选择" type="datetime" transfer></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="结束时间">
              <vxe-input v-model="runningform.endDate" placeholder="日期选择" type="datetime" transfer></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="作业时长">
              <vxe-input v-model="runningform.workHours"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="计划运行时长">
              <vxe-input v-model="runningform.planWorkHours"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="实际运行时长">
              <vxe-input v-model="runningform.realWorkHours"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="停用时长">
              <vxe-input v-model="runningform.stopHours"></vxe-input>
            </el-descriptions-item>
            <el-descriptions-item label="工作量">
              <vxe-input v-model="runningform.workLoad"></vxe-input>
            </el-descriptions-item>

          </el-descriptions>

        </el-scrollbar>

        <div class="footer">
          <el-form :inline="true">
            <el-row>
              <el-col :offset="1">
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="确认" :loading="sloading" @click="saveRunningRecord"></vxe-button>
                </el-form-item>
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="关闭" @click="closeRunningRecord"></vxe-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-container>
  </div>

  <vxe-modal v-model="isEqVisiable" width="45vw" show-footer :mask="false">
    <template #title>
      <span class="text-bold">选择设备</span>
    </template>
    <template #default>
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input style="width: 130px" v-model="searchEqForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findEquiptList" @keyup="keyupEqEnter" @search-click="findEquiptList"></vxe-input>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findEquiptList"></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="equiptTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="equipmentList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column title="序号" width="80">
            <template #default="{ row, rowIndex, column }">
              <span>{{ rowIndex + 1 }}</span>
            </template>
          </vxe-column>
          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="equiptCode" title="编码"></vxe-column>
          <vxe-column field="equiptName" title="名称"></vxe-column>
          <vxe-column field="equiptTypeName" title="设备类型"></vxe-column>
          <vxe-column field="specification" title="型号"></vxe-column>
          <vxe-column field="activationDate" title="启用日期"></vxe-column>
        </vxe-table>
      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelEqEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="confirmEqEvent">确定</vxe-button>
    </template>
  </vxe-modal>

</template>
    <script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { Splitpanes, Pane } from 'splitpanes';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, notifyMessage, notifyType } from '@/utils/common';
import GoBack from '@/components/GoBackNew.vue'; //返回组件

let { proxy }: any = getCurrentInstance();
let backUrl = ref(null);
let pageSize = ref(null);
let pageIndex = ref(null);
let planId = ref(null);
let isEqVisiable = ref(false);
let checkEquiptShow = ref(false);
let checkPersonShow = ref(false);
let lloading = ref(false); //弹框表格数据加载状态
let sloading = ref(false);
let equipmentList: any = reactive([]); //弹框表格数据
let runningClassesList: any = reactive([]); //选择字典
let personList: any = reactive([]); //弹框表格数据

let searchEqForm = reactive({
  searchValue: ''
});

let runningform = reactive({
  id: null,
  runningNo: '',
  equiptId: '',
  equiptCode: '',
  equiptName: '',
  specification: '', //设备型号
  classes: '',
  startPersonId: '',
  startPersonName: '',
  shutPersonId: '',
  shutPersonName: '',
  startDate: '',
  endDate: '',
  runningStatus: '0',
  workHours: null,
  planWorkHours: null,
  realWorkHours: null,
  stopHours: null,
  workLoad: null,
  seq: 1
});

onMounted(() => {
  findPersonList();
  getDictItemsList(); //批量获取字典
  if (!IsEmpty(proxy.$route.query.url)) {
    backUrl.value = proxy.$route.query.url.toString();
  }
  if (!IsEmpty(proxy.$route.query.pageSize)) {
    pageSize.value = proxy.$route.query.pageSize.toString();
  }
  if (!IsEmpty(proxy.$route.query.pageIndex)) {
    pageIndex.value = proxy.$route.query.pageIndex.toString();
  }

  if (!IsEmpty(proxy.$route.query.id)) {
    runningform.id = proxy.$route.query.id.toString();
    planId.value = proxy.$route.query.id.toString();
  }

  if (!IsEmpty(runningform.id)) {
    findRunningRecordById();
  } else {
    checkEquiptShow.value = true;
    checkPersonShow.value = true;
  }
});

function findPersonList() {
  personList.length = 0; //放入数据前清空数据
  const url = '/api/sys/hisEmployee/getPubEmployeeList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      personList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['runningClasses'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });

  const runningClassess = dictTreeTypeItems.data.find((item: any) => item.code === 'runningClasses');
  runningClassesList.push(...runningClassess.detailDataList);
}
function findRunningRecordById() {
  const url = '/api/eq/eqRunningRecord/findRunningRecordById';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        id: runningform.id
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        if (!IsEmpty(res.data)) {
          Object.assign(runningform, res.data);
          if (runningform.runningStatus == '0') {
            checkEquiptShow.value = true;
          }
          if (runningform.runningStatus == '0' || runningform.runningStatus == '5') {
            checkPersonShow.value = true;
          }
        }
      } else {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function checkEquiptDialog() {
  findEquiptList();
  isEqVisiable.value = true;
}

/**关闭窗体 */
function cancelEqEvent() {
  isEqVisiable.value = false;
}

/**确认选择 */
async function confirmEqEvent() {
  const selectRows = (proxy.$refs.equiptTableRef as any).getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择设备', VxeNotifyType.error);
  } else if (selectRows.length > 1) {
    VxeMessage('只能选择一个设备', VxeNotifyType.error);
  } else {
    let sltEquipt = selectRows[0];
    runningform.equiptId = sltEquipt.id;
    runningform.equiptCode = sltEquipt.equiptCode;
    runningform.equiptName = sltEquipt.equiptName;
    runningform.specification = sltEquipt.specification;

    isEqVisiable.value = false;
  }
}

function findEquiptList() {
  lloading.value = true;
  equipmentList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqEquipment/findEqEquipmentList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchEqForm.searchValue
      }
    })
    .then((res: any) => {
      equipmentList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEqEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findEquiptList();
  }
}

function saveRunningRecord() {
  sloading.value = true;
  if (runningform.id === null) {
    const url = '/api/eq/eqRunningRecord/addRunningRecord';
    const supplier = {
      runningNo: runningform.runningNo,
      equiptId: runningform.equiptId,
      equiptCode: runningform.equiptCode,
      equiptName: runningform.equiptName,
      specification: runningform.specification,
      classes: runningform.classes,
      startPersonId: runningform.startPersonId,
      startPersonName: runningform.startPersonName,
      shutPersonId: runningform.shutPersonId,
      shutPersonName: runningform.shutPersonName,
      startDate: runningform.startDate,
      endDate: runningform.endDate,
      runningStatus: '5',
      workHours: runningform.workHours,
      planWorkHours: runningform.planWorkHours,
      realWorkHours: runningform.realWorkHours,
      stopHours: runningform.stopHours,
      workLoad: runningform.workLoad,
      seq: 1
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('新增成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { planId: res.data.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
        } else {
          VxeMessage('新增失败', VxeNotifyType.error);
        }
        sloading.value = false;
      })
      .catch((err: any) => {
        sloading.value = false;
        console.log(err);
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/api/eq/eqRunningRecord/updateRunningRecord';
    const supplier = {
      id: runningform.id,
      runningNo: runningform.runningNo,
      equiptId: runningform.equiptId,
      equiptCode: runningform.equiptCode,
      equiptName: runningform.equiptName,
      specification: runningform.specification,
      classes: runningform.classes,
      startPersonId: runningform.startPersonId,
      startPersonName: runningform.startPersonName,
      shutPersonId: runningform.shutPersonId,
      shutPersonName: runningform.shutPersonName,
      startDate: runningform.startDate,
      endDate: runningform.endDate,
      runningStatus: '5',
      workHours: runningform.workHours,
      planWorkHours: runningform.planWorkHours,
      realWorkHours: runningform.realWorkHours,
      stopHours: runningform.stopHours,
      workLoad: runningform.workLoad,
      seq: 1
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('修改成功', VxeNotifyType.success);
          proxy.$router.push({ path: backUrl.value, query: { planId: res.data.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
        } else {
          VxeMessage('修改失败', VxeNotifyType.error);
        }
        sloading.value = false;
      })
      .catch((err: any) => {
        sloading.value = false;
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

function closeRunningRecord() {
  proxy.$router.push({ path: backUrl.value, query: { planId: runningform.id, pageSize: pageSize.value, pageIndex: pageIndex.value } });
}

function changeStartPerson(row: any) {
  for (const item of personList) {
    if (item.id == row.value) {
      runningform.startPersonName = item.name;
    }
  }
}

function changeShutPerson(row: any) {
  for (const item of personList) {
    if (item.id == row.value) {
      runningform.shutPersonName = item.name;
    }
  }
}
</script>
<style lang="scss" scoped>
#eqRepairEditDiv {
  .el-descriptions {
    margin-top: 10px;
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    box-shadow: 8px 8px 15px #909399;
    background-color: $bg-gray;
    z-index: 9999;
    .el-form {
      transform: translateX(5%);
    }
    .el-form-item {
      margin-bottom: 0;
      margin-right: 12px;
    }
  }
}
</style>